package com.reminiscence.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings.Secure;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;

import com.reminiscence.classes.Utente;
import com.reminiscence.database.OperazioniDB;
import com.reminiscence.main.MainActivity;
import com.reminiscence.main.ProfiloCompleto;
import com.reminiscence.main.R;

public class Utils
{

	public static boolean isConnectingToInternet(Context c)
	{
		boolean ret = false;
		Context context = c;
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		
		if (connectivity != null)
		{
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
			{
				for (int i = 0; i < info.length; i++)
				{
					if (info[i].getState() == NetworkInfo.State.CONNECTED)
					{
						ret = true;
					}
				}
			}
		}
		return ret;
    }
	
	public static String strTomd5(String input)
	{
        String md5 = null;
         
        if(null == input) return null;
         
        try
        {
        	MessageDigest digest = MessageDigest.getInstance("MD5");
        	digest.update(input.getBytes(), 0, input.length());
        	md5 = new BigInteger(1, digest.digest()).toString(16);
 
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        return md5;
    }
	
	public static String getDeviceID(Context c)
	{
		return Secure.getString(c.getContentResolver(), Secure.ANDROID_ID); 
	}
	
	public static void writeUnPwd(Context c, Utente u)
	{
		FileOutputStream fos;
		
		try
		{
			 fos = c.openFileOutput("Reminiscence", Context.MODE_PRIVATE);
			 try
			 {
				fos.write(u.nomeUtente.getBytes());
				fos.write(System.getProperty("line.separator").getBytes());
				fos.write(u.password.getBytes());
				fos.write(System.getProperty("line.separator").getBytes());
				fos.close();
			 }
			 catch (IOException e)
			 {
				e.printStackTrace();
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	public static Boolean readUnPwd(Context c, Utente u)
	{
		Boolean ret = true;
		
		FileInputStream fis;
		InputStream is;
		Scanner sc;
		
		try
		{
			fis = c.openFileInput("Reminiscence");
			is = (InputStream)fis;
			sc = new Scanner(is);
			u.nomeUtente = sc.nextLine();
			u.password = sc.nextLine();
			try
			{
				fis.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		catch (FileNotFoundException e)
		{
			ret = false;
		}
		return ret;
	}
	public static Boolean checkEmail(String s)
	{
		Boolean ret = false;
		Integer k=0;
		Integer j=0;
		Integer w=0;
		
		if (MainActivity.utente.eMail.contains("@"))
		{
			k = 1;
			j = MainActivity.utente.eMail.indexOf("@");
		}
		
		String tmp = s.substring(j, s.length());
		if (MainActivity.utente.eMail.contains("."))
		{
			w = MainActivity.utente.eMail.indexOf(".");
		}
		
		
		if(w > 0 && k > 0 )
		{
			ret = true;
		}
		return ret;
	}
	public static Boolean checkDate(String s)
	{
		Boolean ret = false;
        Boolean g = true;
        Boolean m = true;
        Boolean a = true;
        
		int giorno = 0;
		int mese = 0;
		int anno = 0;
		
		int pb = s.indexOf("/");
		int sb = s.indexOf("/", pb+1);
		
		if (pb > 0 && sb > 0)
		{
			giorno = Integer.parseInt(s.substring(0, pb));
			mese = Integer.parseInt(s.substring(pb+1, sb));
			anno = Integer.parseInt(s.substring(sb+1, s.length()));
            
            if (anno < 1900)
            {
                a = false;
            }
            
            if (mese < 1 || mese > 12)
            {
                m = false;
            }
            
            if (m)
            {
                if (mese == 2)
                {
                    if (giorno < 1 || giorno > 29)
                    {
                        g = false;
                    }
                }
                else
                {
                    if (giorno < 1 || giorno > 31)
                    {
                        g = false;
                    }
                }
            }
            
            if (g && m && a)
            {
                ret = true;
            }
		}
		
		return ret;
	}
	
	public static String formatDate(String s)
	{
		String ret = "";
        
        String giorno = "";
		String mese = "";
		String anno = "";
        
		int pb = s.indexOf("/");
		int sb = s.indexOf("/", pb+1);
        
        giorno = s.substring(0, pb);
        mese = s.substring(pb+1, sb);
        anno = s.substring(sb+1, s.length());
        
        String tmp = "0";
        if (giorno.length() < 2)
        {
            giorno = tmp + giorno;
        }
        
        if (mese.length() < 2)
        {
            mese = tmp + mese;
        }
        
        ret = giorno.concat("/").concat(mese).concat("/").concat(anno);
         
		return ret;
	}
	
	public static void showAlert(final Activity a, String message, String type, String title)
	{
		final String t = type;
		AlertDialog.Builder miaAlert = new AlertDialog.Builder(a);
		miaAlert.setTitle(title);
		miaAlert.setMessage(message);
		miaAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{					
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					if (t == "passLen" || t == "passRep")
					{
						EditText p1 = (EditText)a.findViewById(R.id.edtPassword);
						EditText p2 = (EditText)a.findViewById(R.id.edtRPassword);
						p1.setText("");
						p2.setText("");
					}
					if (t == "data")
					{
						EditText p1 = (EditText)a.findViewById(R.id.edtDataN);
						p1.setText("");
					}
					if (t == "loginSucc")
					{
						Intent i = new Intent(a, ProfiloCompleto.class);
						i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						a.startActivity(i);
					}
					if (t == "loginFail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtLogInId);
						EditText t2 = (EditText)a.findViewById(R.id.edtLogInPassword);
						t1.setText("");
						t1.requestFocus();
						t2.setText("");
					}
					if(t == "InsertFail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtStoria);
						t1.requestFocus();						
					}
					if(t == "ErroreStatoCivile")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtStaCiv);
						t1.requestFocus();
					}
					if(t == "ErroreEmail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtEMail);
						t1.requestFocus();
					}
					if(t == "ErroreTitoloStudio")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtTitoloStudio);
						t1.requestFocus();
					}
					if(t == "ErroreResidenza")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtResidenza);
						t1.requestFocus();
					}
					if(t == "ErroreProfessionePassata")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtProfPrinc);
						t1.requestFocus();
					}
					if(t == "ErroreProfessioneAttuale")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtProfAt);
						t1.requestFocus();
					}
					if(t == "InsertTitoloFail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtTitoloStoria);
						t1.requestFocus();
					}
					if(t == "InsertTestoFail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtStoria);
						t1.requestFocus();
					}
					if(t == "InsertLuogoFail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtLuogo);
						t1.requestFocus();
					}
					if(t == "InsertAnnoFail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtAnno);
						t1.requestFocus();
					}
					if(t == "ErroreFormatoEmail")
					{
						EditText t1 = (EditText)a.findViewById(R.id.edtEMail);
						t1.requestFocus();
					}
					
					return;
				}
			});
		AlertDialog alert = miaAlert.create();
		alert.show();
	}
	
	public static void uploadFoto(Activity a, Bitmap bitmapOrg, String fileName)
	{
		InputStream is;
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		
		bitmapOrg.compress(Bitmap.CompressFormat.JPEG,90, bao);
		byte ba[] = bao.toByteArray();
		String ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("image", ba1));
		params.add(new BasicNameValuePair("fileName", fileName));
		Boolean ret = false; 
		try
		{
			ret =  (Boolean)(new OperazioniDB(a, "uploadFoto", params).execute().get());
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
